package com.gocoolmall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gocoolmall.common.utils.R;
import com.gocoolmall.feign.ProductFeignService;
import com.gocoolmall.order.interceptor.CartInterceptor;
import com.gocoolmall.service.CartService;
import com.gocoolmall.vo.Cart;
import com.gocoolmall.vo.CartItem;
import com.gocoolmall.vo.SkuInfoVo;
import com.gocoolmall.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    private final String CART_PREFIX = "gocoolmall:cart:";
    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        System.out.println("添加到购物车开始");
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        //添加新的商品到购物车
        if (StringUtils.isEmpty(res)) {
            System.out.println("购物车无此商品");
            CartItem cartItem = new CartItem();
            //1.远程查询当前要添加的商品信息
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询当前要添加的商品信息
                R info = productFeignService.info(skuId);
                SkuInfoVo data = info.getDate("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                //2、商品添加都购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setSkuId(skuId);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
            }, executor);

            //2、远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                List<String> value = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(value);
            }, executor);

            //3、添加到redis
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);
            System.out.println("业务执行结束" + cartItem);
            return cartItem;
        } else {
            //购物车有此商品，修改数量
            System.out.println("购物车有此商品");
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            System.out.println(cartItem.getCount());

            //更新redis
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            System.out.println("业务执行结束" + cartItem);
            return cartItem;
        }
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String str = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(str, CartItem.class);
        return cartItem;
    }

    /**
     * 获取整个购物车
     * @return
     */
    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //登录
            //1、如果临时购物车的数据还没有进行合并。
            String tempKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItem = getCartItems(tempKey);
            if (tempCartItem != null) {
                //临时购物车有数据，需要合并
                for (CartItem item : tempCartItem) {
                    try {
                        addToCart(item.getSkuId(),item.getCount());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                //清除临时购物车的数据。
                clearCart(tempKey);

            }
            //2、获取登录后的购物车的数据【包含合并过来的临时购物车的数据，和登录后的购物车的数据】
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //没有登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车的所有购物项
            List<CartItem> cartItem = getCartItems(cartKey);
            cart.setItems(cartItem);
        }
        return cart;
    }

    /**
     * 清空购物车数据
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);

    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        cartOps.put(skuId.toString(),s);
    }

    /**
     * 修改购物项数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeIteCcount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);

        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItem));
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null){
            return null;
        }else {
            String cartKye = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems =getCartItems(cartKye);
            //获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream().
                    filter(item -> item.getCheck()).
                    map(item ->{
                        R price = productFeignService.getPrice(item.getSkuId());
                        String date = (String)price.get("date");
                        //跟新为最新价格
                        item.setPrice(new BigDecimal(date));
                        return item;
                    }).
                    collect(Collectors.toList());
            return collect;
        }


    }

    /**
     * 获取临时购物车的所有购物项
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取到我们的要操作的购物车
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        System.out.println("共享线程数据" + userInfoTo);
        //1、
        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }
}
